import httpx
import logging
from datetime import datetime, date, timedelta
from typing import List, Dict, Optional
from .base import DataSourceProvider, RateData

logger = logging.getLogger(__name__)


class ExchangeRateHostProvider(DataSourceProvider):
    """ExchangeRate.host 数据源提供器"""
    
    def __init__(self):
        self.base_url = "https://api.exchangerate.host"
        self.timeout = 30.0
    
    def get_name(self) -> str:
        return "ExchangeRate.host"
    
    async def get_latest_rates(self, base: str = "JPY", quotes: List[str] = None) -> List[RateData]:
        """获取最新汇率"""
        if quotes is None:
            quotes = ["CNY", "USD"]
        
        url = f"{self.base_url}/latest"
        params = {
            "base": base,
            "symbols": ",".join(quotes)
        }
        
        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                response = await client.get(url, params=params)
                response.raise_for_status()
                data = response.json()
                
                if not data.get("success", False):
                    raise Exception(f"API返回失败: {data.get('error', {}).get('info', 'Unknown error')}")
                
                rates = data.get("rates", {})
                timestamp = datetime.fromtimestamp(data.get("timestamp", 0))
                
                result = []
                for quote in quotes:
                    if quote in rates:
                        result.append(RateData(
                            timestamp=timestamp,
                            base=base,
                            quote=quote,
                            rate=rates[quote]
                        ))
                
                logger.info(f"从 {self.get_name()} 获取到 {len(result)} 条最新汇率数据")
                return result
                
        except Exception as e:
            logger.error(f"从 {self.get_name()} 获取最新汇率失败: {e}")
            raise
    
    async def get_historical_rates(
        self, 
        base: str = "JPY", 
        quotes: List[str] = None,
        start_date: date = None,
        end_date: date = None
    ) -> List[RateData]:
        """获取历史汇率"""
        if quotes is None:
            quotes = ["CNY", "USD"]
        
        if start_date is None:
            start_date = date.today() - timedelta(days=30)
        if end_date is None:
            end_date = date.today()
        
        url = f"{self.base_url}/timeseries"
        params = {
            "start_date": start_date.strftime("%Y-%m-%d"),
            "end_date": end_date.strftime("%Y-%m-%d"),
            "base": base,
            "symbols": ",".join(quotes)
        }
        
        try:
            async with httpx.AsyncClient(timeout=self.timeout) as client:
                response = await client.get(url, params=params)
                response.raise_for_status()
                data = response.json()
                
                if not data.get("success", False):
                    raise Exception(f"API返回失败: {data.get('error', {}).get('info', 'Unknown error')}")
                
                rates_data = data.get("rates", {})
                result = []
                
                for date_str, rates in rates_data.items():
                    timestamp = datetime.strptime(date_str, "%Y-%m-%d")
                    for quote in quotes:
                        if quote in rates:
                            result.append(RateData(
                                timestamp=timestamp,
                                base=base,
                                quote=quote,
                                rate=rates[quote]
                            ))
                
                logger.info(f"从 {self.get_name()} 获取到 {len(result)} 条历史汇率数据 ({start_date} 到 {end_date})")
                return result
                
        except Exception as e:
            logger.error(f"从 {self.get_name()} 获取历史汇率失败: {e}")
            raise
